package com.freight.common.security.service;

import com.freight.common.core.constant.CacheConstants;
import com.freight.common.core.constant.SecurityConstants;
import com.freight.common.core.utils.IdUtils;
import com.freight.common.core.utils.JwtUtils;
import com.freight.common.redis.service.RedisService;
import com.freight.common.security.utils.SecurityUtils;
import com.freight.tws.api.model.LoginDriver;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 手机APP端token验证处理
 */
@Component
public class AppTokenService {

    @Autowired
    private RedisService redisService;

    private final static long EXPIRE_TIME = CacheConstants.EXPIRATION * 2400;

    private final static String ACCESS_TOKEN = CacheConstants.APP_TOKEN_KEY;

    /**
     * 创建令牌
     */
    public Map<String, Object> createToken(LoginDriver loginDriver) {
        // 生成token
        String token = IdUtils.fastUUID();
        loginDriver.setToken(token);

        // 存放新token之前，先将此人已有的token删除，保证缓存中只有一份此人的token
        removeTokenByUserid(loginDriver.getDriverId());

        // token保存到缓存
        refreshToken(loginDriver);

        // Jwt存储信息
        Map<String, Object> claimsMap = new HashMap<>();
        claimsMap.put(SecurityConstants.USER_KEY, token);
        claimsMap.put(SecurityConstants.DETAILS_USER_ID, loginDriver.getDriverId());
        claimsMap.put(SecurityConstants.DETAILS_USERNAME, loginDriver.getTelephone());

        // 接口返回信息
        Map<String, Object> map = new HashMap<>();
        map.put("access_token", JwtUtils.createToken(claimsMap));
        map.put("expires_in", EXPIRE_TIME);
        return map;
    }

    /**
     * 获取身份信息
     */
    public LoginDriver getLoginUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = SecurityUtils.getToken(request);
        return getLoginUser(token);
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginDriver getLoginUser(String token)
    {
        LoginDriver user = null;
        try
        {
            if (StringUtils.isNotEmpty(token))
            {
                String userkey = JwtUtils.getUserKey(token);
                user = redisService.getCacheObject(getTokenKey(userkey));
                return user;
            }
        }
        catch (Exception e)
        {
        }
        return user;
    }

    /**
     * 根据登录id获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginDriver getLoginUserByLoginId(String loginUserid) {
        LoginDriver user = null;
        Collection<String> keys = redisService.keys(ACCESS_TOKEN + "*");
        for (String key : keys) {
            LoginDriver loginDriver = redisService.getCacheObject(key);
            if(loginDriver.getDriverId().equals(loginUserid)) {
                user = loginDriver;
            }
        }
        return user;
    }

    public void delLoginUser(String token)
    {
        if (StringUtils.isNotEmpty(token))
        {
            String userkey = JwtUtils.getUserKey(token);
            redisService.deleteObject(getTokenKey(userkey));
        }
    }

    /**
     * 删除某用户所有的缓存token
     * @param loginUserid
     */
    private void removeTokenByUserid(String loginUserid) {
        Collection<String> keys = redisService.keys(ACCESS_TOKEN + "*");
        for (String key : keys) {
            LoginDriver loginDriver = redisService.getCacheObject(key);
            if(loginDriver.getDriverId().equals(loginUserid)) {
                redisService.deleteObject(key);
            }
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginDriver 登录信息
     */
    public Long refreshToken(LoginDriver loginDriver)
    {
        loginDriver.setLoginTime(System.currentTimeMillis());
        loginDriver.setExpireTime(loginDriver.getLoginTime() + EXPIRE_TIME);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginDriver.getToken());
        redisService.setCacheObject(userKey, loginDriver, EXPIRE_TIME, TimeUnit.SECONDS);
        return EXPIRE_TIME;
    }

    private String getTokenKey(String token) {
        return ACCESS_TOKEN + token;
    }

}